<script setup>
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  LegendComponent,
  ToolboxComponent,
  DataZoomComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { getActivityTimeTrend } from '../../api/activity';

// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  LegendComponent,
  ToolboxComponent,
  DataZoomComponent,
  LineChart,
  CanvasRenderer
]);

const props = defineProps({
  userId: {
    type: String,
    required: true
  },
  dataType: {
    type: String,
    default: 'distance', // distance, duration, calorie
  },
  dateRange: {
    type: Object,
    default: () => ({})
  }
});

const loading = ref(true);
const chartRef = ref(null);
const chartInstance = ref(null);
const trendData = ref({
  dates: [],
  distance: [],
  duration: [],
  calorie: []
});

// 获取数据并初始化图表
const initChart = async () => {
  loading.value = true;
  try {
    const params = {
      startDate: props.dateRange.startDate,
      endDate: props.dateRange.endDate
    };
    
    trendData.value = await getActivityTimeTrend(props.userId, params);
    renderChart();
  } catch (error) {
    console.error('获取数据失败', error);
  } finally {
    loading.value = false;
  }
};

// 渲染图表
const renderChart = () => {
  if (!chartRef.value || !trendData.value.dates.length) return;
  
  // 销毁旧实例
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }
  
  // 创建新实例
  chartInstance.value = echarts.init(chartRef.value);
  
  // 图表标题
  const titles = {
    distance: '距离趋势 (km)',
    duration: '时长趋势 (分钟)',
    calorie: '卡路里趋势 (kcal)'
  };
  
  // 数据系列
  const seriesData = {
    distance: trendData.value.distance,
    duration: trendData.value.duration,
    calorie: trendData.value.calorie
  };
  
  // 图表配置
  const option = {
    title: {
      text: titles[props.dataType],
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: function(params) {
        const date = params[0].axisValue;
        const value = params[0].data;
        const unit = props.dataType === 'distance' ? 'km' : 
                     props.dataType === 'duration' ? '分钟' : 'kcal';
        return `${date}<br/>${params[0].seriesName}: ${value} ${unit}`;
      }
    },
    toolbox: {
      feature: {
        saveAsImage: {},
        dataZoom: {
          yAxisIndex: 'none'
        },
        restore: {}
      },
      right: 20
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        start: 0,
        end: 100
      }
    ],
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: trendData.value.dates,
      axisLabel: {
        formatter: (value) => {
          const date = new Date(value);
          return `${date.getMonth()+1}/${date.getDate()}`;
        }
      }
    },
    yAxis: {
      type: 'value',
      name: props.dataType === 'distance' ? '公里' : 
            props.dataType === 'duration' ? '分钟' : '卡路里',
      nameLocation: 'end',
      nameGap: 15,
      scale: true
    },
    series: [
      {
        name: props.dataType === 'distance' ? '运动距离' : 
              props.dataType === 'duration' ? '运动时长' : '卡路里消耗',
        type: 'line',
        data: seriesData[props.dataType],
        smooth: true,
        showSymbol: false,
        areaStyle: {
          opacity: 0.3
        },
        lineStyle: {
          width: 3
        },
        markPoint: {
          data: [
            { type: 'max', name: '最大值' },
            { type: 'min', name: '最小值' }
          ]
        },
        markLine: {
          data: [
            { type: 'average', name: '平均值' }
          ]
        }
      }
    ],
    color: [
      props.dataType === 'distance' ? '#1ac963' : 
      props.dataType === 'duration' ? '#ffa940' : '#ff4d4f'
    ]
  };
  
  // 设置图表配置
  chartInstance.value.setOption(option);
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    chartInstance.value && chartInstance.value.resize();
  });
};

// 监听属性变化时重新渲染图表
watch(() => props.dataType, () => {
  renderChart();
});

watch(() => props.dateRange, () => {
  initChart();
}, { deep: true });

watch(() => props.userId, () => {
  initChart();
});

// 组件挂载时初始化图表
onMounted(() => {
  initChart();
});
</script>

<template>
  <div class="chart-container">
    <div v-if="loading" class="loading">加载中...</div>
    <div v-else-if="trendData.dates.length === 0" class="no-data">暂无数据</div>
    <div ref="chartRef" class="chart" v-else></div>
  </div>
</template>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 300px;
  position: relative;
}
.chart {
  width: 100%;
  height: 100%;
}
.loading, .no-data {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  min-height: 300px;
  color: #999;
  font-size: 14px;
}
</style> 